<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #tableTitle>
        <div class="ml-2">
          <span class="pr-1">{{ tableTitle }}</span>
          <a-select
            v-if="props.entityType != 'ASSET' && props.entityType != 'TENANT_PROFILE'"
            style="margin-left: 10px; width: auto"
            :options="options"
            v-model:value="optionsValue"
            @change="handleChange"
          />
        </div>
      </template>
      <template #toolbar>
        <a-button v-show="optionsValue != 'CLIENT_SCOPE'" type="primary" @click="handleAdd"
          >添加属性</a-button
        >
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: ICON.EDIT,
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                ifShow: () => true,
                onClick: handleEdit.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <Modal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script setup lang="ts">
  import { defineProps, ref, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { Select as ASelect, Alert, Tooltip } from 'ant-design-vue';
  import Icon from '/@/components/Icon';
  import { tableSchema, formSchema, options } from './index.data';
  import Modal from './components/Modal.vue';
  import { ICON } from '/@/enums/iconEnum';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    getClientScope,
    getServeScope,
    getSharedScope,
    saveEntityAttributes,
    deleteEntityAttribute,
  } from '/@/api/thingsborad/entity/entity';
  import {
    attributesParams,
    attributesResponse,
    saveAttributesParams,
  } from '/@/api/thingsborad/entity/model/entityModel';
  import {
    publicDrawerTableFormStyleSetting,
    tableStyleSetting,
  } from '/@/settings/thingsBoardDesign';

  const props = defineProps({
    isComponent: {
      type: Boolean,
      default: true,
    },
    entityType: {
      type: String,
      default: '',
    },
    entityId: {
      type: String,
      default: '',
    },
  });
  const tableTitle = ref('客户端属性');
  const optionsValue = ref<string>('CLIENT_SCOPE');
  // 多选数据
  const checkedKeys = ref<any>([]);
  const { createConfirm } = useMessage();

  const [registerTable, { setProps, reload }] = useTable({
    ...tableStyleSetting,
    fetchSetting: {
      pageField: 'page',
      sizeField: 'pageSize',
      listField: 'data',
      totalField: 'totalElements',
    },
    pagination: { pageSizeOptions: ['10', '20', '30'] },
    formConfig: {
      layout: 'horizontal',
      schemas: formSchema,
      ...publicDrawerTableFormStyleSetting,
      actionColOptions: {
        md: { span: 12, offset: 0 },
        lg: { span: 8, offset: 8 },
        xl: { span: 6, offset: 12 },
        xxl: { span: 6, offset: 12 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  const [registerModal, { openModal }] = useModal();
  // 添加
  const handleAdd = () => {
    openModal(true, { mode: 'add', optionsValue: optionsValue.value });
  };
  // 编辑
  const handleEdit = (record: Recordable) => {
    openModal(true, {
      mode: 'edit',
      optionValue: optionsValue.value,
      record,
    });
  };
  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除${checkedKeys.value.length}个属性吗？`,
      content: '注意,确认后所有选中的属性都会被删除。',
      onOk: async () => {
        setProps({ loading: true });
        for (const item of checkedKeys.value) {
          await deleteEntityAttribute({
            entityType: props.entityType,
            entityId: props.entityId,
            scope: optionsValue.value,
            obj: {
              keys: item,
            },
          });
        }
        reload();
        checkedKeys.value = [];
      },
    });
  };
  // 属性表格切换
  const handleChange = (value: string) => {
    let api: any;
    switch (value) {
      case 'CLIENT_SCOPE':
        tableTitle.value = '客户端属性';
        api = getClientScope;
        break;
      case 'SERVER_SCOPE':
        tableTitle.value = '服务端属性';
        api = getServeScope;
        break;
      case 'SHARED_SCOPE':
        tableTitle.value = '共享属性';
        api = getSharedScope;
        break;
    }
    setProps({ api });
    reload();
  };

  // 成功
  const handleSuccess = async ({ values }) => {
    let params: saveAttributesParams = {
      entityType: props.entityType,
      entityId: props.entityId,
      scope: optionsValue.value,
      key: values.keyName,
    };
    switch (values.valueType) {
      case 'string':
        params.value = values.stringValue;
        break;
      case 'integer':
        params.value = values.integerValue;
        break;
      case 'decimal':
        values.decimalValue = parseFloat(values.decimalValue);
        params.value = values.decimalValue;
        break;
      case 'boolean':
        params.value = values.booleanValue;
        break;
      case 'json':
        values.jsonValue = JSON.parse(values.jsonValue);
        params.value = values.jsonValue;
        break;
    }
    await saveEntityAttributes(params);
    reload();
  };

  // 初始化
  onMounted(() => {
    if (props.isComponent) {
      if (props.entityType === 'ASSET' || props.entityType === 'TENANT_PROFILE') {
        optionsValue.value = 'SERVER_SCOPE';
        tableTitle.value = '服务端属性';
      }
      setProps({
        api: getClientScope,
        columns: tableSchema,
        beforeFetch: (value) => {
          let params: attributesParams = {
            entityType: props.entityType,
            entityId: props.entityId,
            scope: optionsValue.value,
            key: value.keyName,
            responseDataType: 'values',
          };
          return params;
        },
        afterFetch: (res) => {
          let list: attributesResponse[] = [];
          res.length != 0
            ? res.forEach((item: attributesResponse) => {
                let tableItem: attributesResponse = {
                  id: item.key,
                  key: item.key,
                  lastUpdateTs: item.lastUpdateTs,
                  value:
                    typeof item.value == 'object' || typeof item.value == 'boolean'
                      ? JSON.stringify(item.value)
                      : item.value,
                };
                if (typeof item.value == 'string') {
                  tableItem.type = 'string';
                }
                if (Number.isInteger(item.value)) {
                  tableItem.type = 'integer';
                }
                if (typeof item.value === 'number' && !Number.isInteger(item.value)) {
                  tableItem.type = 'decimal';
                  tableItem.value = String(item.value);
                }
                if (typeof item.value == 'boolean') {
                  tableItem.type = 'boolean';
                }
                if (typeof item.value == 'object') {
                  tableItem.type = 'json';
                }
                list.push(tableItem);
              })
            : null;

          return list;
        },
      });
    }
  });
</script>
